<template>
  <section class="todoapp">
    <todo-header @appendItem="appendItem"></todo-header>
    <todo-main :list="showList" @removeItem="removeItem" @changeDone="changeDone"></todo-main>
    <todo-footer :list="showList" @clearItem="clearItem" @dataDisplay="dataDisplay"></todo-footer>
  </section>
</template>

<script>
import todoHeader from "./components/todoHeader.vue";
import todoMain from "./components/todoMain.vue";
import todoFooter from "./components/todoFooter.vue";
export default {
  components: {
    todoFooter,
    todoHeader,
    todoMain
  },
  data() {
    return {
      // list: [
      //   { id: 1, name: "吃饭", isDone: true },
      //   { id: 2, name: "睡觉", isDone: false },
      //   { id: 3, name: "打豆豆", isDone: true }
      // ],
      list: JSON.parse(localStorage.getItem("list") || "[]"),
      type: ""
    };
  },
  methods: {
    removeItem(id) {
      console.log(id);
      const index = this.list.findIndex(item => item.id === id);
      this.list.splice(index, 1);
    },
    changeDone(id) {
      const item = this.list.find(item => item.id === id);
      item.isDone = !item.isDone;
    },
    appendItem(item) {
      this.list.push({
        id: Date.now(),
        name: item,
        isDone: false
      });
    },
    dataDisplay(type) {
      console.log(type);
      this.type = type;
    },
    clearItem() {
      this.list = this.list.filter(item => !item.isDone);
    }
  },
  computed: {
    showList() {
      if (this.type === "active") {
        return this.list.filter(item => !item.isDone);
      } else if (this.type === "completed") {
        return this.list.filter(item => item.isDone);
      } else {
        return this.list;
      }
    }
  },
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem("list", JSON.stringify(this.list));
      }
    }
  }
};
</script>

<style></style>
